/*
 * Copyright (C) 2011 Nicola Bonzanni
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package nl.vu.few.ibivu.jlemon;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import nl.vu.few.ibivu.jlemon.concepts.AddNodeHandler;
import nl.vu.few.ibivu.jlemon.concepts.ClearHandler;
import nl.vu.few.ibivu.jlemon.concepts.EraseNodeHandler;
import nl.vu.few.ibivu.jlemon.concepts.Graph;
import nl.vu.few.ibivu.jlemon.concepts.Node;

public class NodeMap<N extends Node & Comparable<N>, V> extends
		AbstractVectorMap<N, V> implements AddNodeHandler<N>,
		EraseNodeHandler<N>, ClearHandler, Serializable {

	private static final long serialVersionUID = 1L;
	Graph<N, ?> graph;
	
	public NodeMap(NodeMap<N,V> nodeMap) {
		super(nodeMap.keySet(), nodeMap.graph.maxNodeId() + 1);
		this.graph = nodeMap.graph;
		putAll(nodeMap);
	}

	public NodeMap(Graph<N, ?> graph) {
		super(new AsNodeSet<N>(graph), graph.maxNodeId() + 1, null);
		this.graph = graph;
	}

	public NodeMap(Graph<N, ?> graph, V initValue) {
		super(new AsNodeSet<N>(graph), graph.maxNodeId() + 1, initValue);
		this.graph = graph;
	}
	
	public Graph<N, ?> getGraph() {
		return graph;
	}

	@Override
	protected int getId(Object key) {
		if (graph.getNodeClass().isInstance(key)) {
			return graph.id(graph.getNodeClass().cast(key));
		}
		return -1;
	}

	@Override
	protected N getItem(int id) {
		return graph.nodeFromId(id);
	}

	@Override
	public void onClear() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onEraseNode(N... node) {
		for (int i = 0; i < node.length; i++) {
			put(node[i], null);
		}
	}

	@Override
	public void onAddNode(N... node) {
		adjustInternalContainer();
	}

	/**
	 * Custom deserialization is needed.
	 */
	@SuppressWarnings("unchecked") // explain!
	private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
		stream.defaultReadObject();
		// manually deserialize and init superclass
		NodeMap<N,V>.InternalState state = (NodeMap<N,V>.InternalState) stream.readObject();
		init(state);
	}

	/**
	 * Custom serialization is needed.
	 */
	private void writeObject(ObjectOutputStream stream) throws IOException {
		stream.defaultWriteObject();
		// manually serialize superclass
		stream.writeObject(getInternalState());
	}

}
